package tcp.longconnection.client.util;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.prefs.BackingStoreException;

import tcp.longconnection.client.protocol.BasicProtocol;

public class SocketUtil {

	/**
	 * 
	 * Description:int转byte数组
	 * 
	 * @author wanghao DateTime 2017年2月23日 下午4:48:35
	 * @param value
	 * @return
	 */
	public static byte[] intToByte(int value) {
		byte[] src = new byte[4];
		src[0] = (byte) ((value >> 24) & 0xff);
		src[1] = (byte) ((value >> 16) & 0xff);
		src[2] = (byte) ((value >> 8) & 0xff);
		src[3] = (byte) (value & 0xff);
		return src;
	}

	public static int byteToInt(byte[] src, int offset) {
		int value;
		value = (int) (((src[offset] & 0xFF) << 24)
				| ((src[offset + 1] & 0xFF) << 16)
				| ((src[offset + 2] & 0xFF) << 8) | (src[offset + 3] & 0xFF));
		return value;
	}
	
	/**
	 * 
	 *  Description:将协议内容 写入到流中
	 *  @author wanghao  DateTime 2017年2月27日 下午5:40:05
	 *  @param basicProtocol
	 *  @param outputStream
	 */
	public static void writeContent2Stream(BasicProtocol basicProtocol, OutputStream outputStream) {
		BufferedOutputStream bos = new BufferedOutputStream(outputStream);
		byte[] content = basicProtocol.getContentData();
		int length = content.length;
		byte[] head = intToByte(length);
		try {
			bos.write(head);
			bos.write(content);
			bos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
